﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.UI.WebControls;
using EOSCRM.Util ;
using EOSCRM.Domain;
using EOSCRM.Web.Common;
using EOSCRM.Dao;
using EOSCRM.Web.Shared;
using EOSCRM.Web.UserControls;


namespace EOSCRM.Web.Forms.ChucNang
{
    public partial class QLTienLuong : Authentication
    {
        private readonly ChamCongDao _objDao = new ChamCongDao();
        private readonly LoDao _loDao = new LoDao();
        private readonly NhanVienDao _nvDao = new NhanVienDao();
        private readonly KhuVucDao _khuVucDao = new KhuVucDao();
        private readonly CongTyDao _congtyDao = new CongTyDao();

        private string CreateID()
        {
            string ma = "";
            ma = ma + "CC";
            ma = ma + DateTime.Now.Day.ToString("D2") + DateTime.Now.Month.ToString("D2") + DateTime.Now.Year.ToString("D4") + DateTime.Now.Hour.ToString("D2") + DateTime.Now.Minute.ToString("D2") + DateTime.Now.Second.ToString("D2");
            return ma;
        }

        private CHAMCONG ItemObj
        {
            get
            {
                if (!ValidateData())
                    return null;

                var kv = new CHAMCONG
                {
                    MaChamCong = txtMa.Text.Trim(),
                    NgayChamCong = ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value,
                    MaNV = ddlNhanVien.SelectedValue,
                    Luong = int.Parse(txtLuong.Text.Trim()),
                    GhiChu = (txtnotes.Text.Trim()),
                    ISNGHIPHEP = rdYes.Checked,
                    Lo = ddlLo.SelectedValue,
                    MaNVNhap=LoginInfo.MaNV
                    //STARTCODE = txtMaKV.Text.Trim(),
                    //DACBIET = false
                };

                return kv;
            }
        }

        private Mode UpdateMode
        {
            get
            {
                try
                {
                    if (Session[SessionKey.MODE] != null)
                    {
                        var mode = Convert.ToInt32(Session[SessionKey.MODE]);
                        return (mode == Mode.Update.GetHashCode()) ? Mode.Update : Mode.Create;
                    }

                    return Mode.Create;
                }
                catch (Exception)
                {
                    return Mode.Create;
                }
            }
            set
            {
                Session[SessionKey.MODE] = value.GetHashCode();
            }
        }



        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!Page.IsPostBack)
                {
                    ClearForm();
                    lbngayhientai.Text = DateTime.Now.ToString("dd/MM/yyyy"); 
                    LoadKhuVuc();
                    LoadLo(ddlKhuVuc.SelectedValue);
                    LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).HasValue ? ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value : DateTime.Now);
                    LoadTienLuongLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).HasValue ? ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value : DateTime.Now);
                    if (ddlNhanVien.SelectedIndex != -1)
                    {
                        LoadLuongNV(ddlNhanVien.SelectedValue);
                    }    
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }
        
        private void BindDataForGrid()
        {
            var objList = _objDao.GetList(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            gvList.DataSource = objList;
            gvList.PagerInforText = objList.Count.ToString();
            gvList.DataBind();
        }
        
        public bool ValidateData()
        {
            if (ddlLo.SelectedIndex == -1)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Lô"), ddlLo.ClientID);
                return false;
            }
            if (ddlNhanVien.SelectedIndex == -1)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Nhân viên"), ddlNhanVien.ClientID);
                return false;
            }
            try
            {
                int.Parse(txtLuong.Text.Trim());
            }
            catch (Exception)
            {
                ShowError(String.Format(Resources.Message.E_INVALID_DATA, "Lương "), txtLuong.ClientID);
                return false;
            }

            
            return true;
        }

        private void DeleteList()
        {
            try
            {
                // Get list of ids that to be update
                var strIds = Request["listIds"];
                if ((strIds != null) && (!string.Empty.Equals(strIds)))
                {
                    //TODO: check relation before update list

                    var objs = new List<CHAMCONG>();
                    var listIds = strIds.Split(',');

                    // Kiem tra relation ship truoc khi delete
                    foreach (var ma in listIds)
                    {
                        if (_objDao.IsInUse(ma))
                        {
                            var msgIsInUse = new Message(MessageConstants.E_OBJECT_IN_USED, MessageType.Info, "chấm công với mã", ma);

                            CloseWaitingDialog();

                            ShowError(ResourceLabel.Get(msgIsInUse));
                            return;
                        }
                    }

                    //Add ma vao danh sách cần delete
                    objs.AddRange(listIds.Select(ma => _objDao.Get(ma)));

                    if (objs.Count > 0)
                    {
                        var msg = _objDao.DeleteList(objs, UserEventLog.ClientHost(), UserEventLog.ClientIP(), LoginInfo.MaNV);
                        if (msg != null)
                        {
                            CloseWaitingDialog();

                            switch (msg.MsgType)
                            {
                                case MessageType.Error:
                                    ShowError(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Info:
                                    ShowInfor(ResourceLabel.Get(msg));
                                    break;

                                case MessageType.Warning:
                                    ShowWarning(ResourceLabel.Get(msg));
                                    break;
                            }
                        }
                    }
                    else
                    {
                        CloseWaitingDialog();
                    }
                    LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).HasValue ? ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value : DateTime.Now);
                    if (ddlNhanVien.SelectedIndex != -1)
                    {
                        LoadLuongNV(ddlNhanVien.SelectedValue);
                    }  
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        private void ClearForm()
        {
            txtMa.Text = CreateID() ;
            txtMa.ReadOnly = false;

            rdNo.Checked = true;
            rdYes.Checked = false;
            txtLuong.Text = "0";
            txtnotes.Text = "";
            UpdateMode = Mode.Create;

            txtMa.Focus();
            LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).HasValue ? ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value : DateTime.Now);
            if (ddlNhanVien.SelectedIndex != -1)
            {
                LoadLuongNV(ddlNhanVien.SelectedValue);
            }  
        }

        private void BindKhuVuc(CHAMCONG obj)
        {
            if (obj == null)
                return;
            SetControlValue(txtMa.ClientID, obj.MaChamCong);
            SetReadonly(txtMa.ClientID, true);
            SetControlValue(txtLuong.ClientID, obj.Luong.ToString());
            SetControlValue(txtnotes.ClientID, obj.GhiChu.ToString());      
            SetControlValue(ddlNhanVien.ClientID, obj.MaNV);
            upnlInfor.Update();

            if (obj.ISNGHIPHEP == true)
            {
                this.rdYes.Checked = true;
                this.rdNo.Checked = false;
            }
            else
            {
                this.rdNo.Checked = true;
                this.rdYes.Checked = false;
            }
        }
        protected void gvList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
                var makv = e.CommandArgument.ToString();

                switch (e.CommandName)
                {
                    case "EditItem":
                        if (!string.Empty.Equals(makv))
                        {
                            var objDb = _objDao.Get(makv);
                            if (objDb != null)
                            {
                                BindKhuVuc(objDb);
                                UpdateMode = Mode.Update;
                            }
                        }

                        CloseWaitingDialog();

                        break;
                }
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            var info = ItemObj;
            if (info == null)
            {
                CloseWaitingDialog();
                return;
            }

            Message msg;

            // insert new
            if (UpdateMode == Mode.Create)
            {
                if (!HasInsertPermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                } 

                var tontai = _objDao.Get(txtMa.Text.Trim());
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Mã chấm công đã tồn tại", txtMa.ClientID);
                    return;
                }
                tontai = _objDao.GetNV(ddlNhanVien.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Nhân viên này đã chấm công.", ddlNhanVien.ClientID);
                    return;
                }
                msg = _objDao.Insert(info,UserEventLog.ClientHost(),UserEventLog.ClientIP(),LoginInfo.MaNV);

            }
            // update
            else
            {
                if (!HasUpdatePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }
                var tontai = _objDao.GetNV(txtMa.Text.Trim(),ddlNhanVien.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
                if (tontai != null)
                {
                    CloseWaitingDialog();
                    ShowError("Nhân viên này đã chấm công.", ddlNhanVien.ClientID);
                    return;
                }
                msg = _objDao.Update(info, UserEventLog.ClientHost(), UserEventLog.ClientIP(), LoginInfo.MaNV);
            }

            CloseWaitingDialog();

            if (msg == null) return;

            if (msg.MsgType != MessageType.Error)
            {
                ShowInfor(ResourceLabel.Get(msg));

                ClearForm();

                // Refresh grid view
                BindDataForGrid();
                
                upnlGrid.Update();
               
            }
            else
            {
                ShowError(ResourceLabel.Get(msg));
            }
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                // Authenticate
                if (!HasDeletePermission)
                {
                    CloseWaitingDialog();
                    ShowError(Resources.Message.WARN_PERMISSION_DENIED);
                    return;
                }

                DeleteList();
                BindDataForGrid();
                upnlGrid.Update();

                CloseWaitingDialog();
            }
            catch (Exception ex)
            {
                DoError(new Message(MessageConstants.E_EXCEPTION, MessageType.Error, ex.Message, ex.StackTrace));
            }
        }

        protected void btnCancel_Click(object sender, EventArgs e)
        {
            CloseWaitingDialog();
            ClearForm();
        }

        private void LoadNhanVienLo(string ma, DateTime ngay)
        {
            var objList = _nvDao.GetListLoNop(ma, ngay);
            CommonFunc.BindDropDownList(ddlNhanVien, objList, "TenNV", "MaNV", false);
        }

        private void LoadKhuVuc()
        {
            var objList = _khuVucDao.GetList();
            CommonFunc.BindDropDownList(ddlKhuVuc, objList, "TenKhuVuc", "MaKhuVuc", false);
        }
        private void LoadLo(string makv)
        {
            var objList = _loDao.GetListKhuVuc(makv);
            CommonFunc.BindDropDownList(ddlLo, objList, "TenLo", "MaLo", false);
        }

        private void LoadTienLuongLo(string malo, DateTime ngay)
        {
            var objList = _objDao.GetList(malo,ngay);
            gvList.DataSource = objList;
            gvList.DataBind();
        }

        private void LoadLuongNV(string manv)
        {
            var objList = _nvDao.Get(manv);
            var cty = _congtyDao.Get();
            if (objList.LOAILUONG1.TenLoaiLuong.Contains("Lương cứng"))
            {
                
                int luong = (int)(objList.MucLuong / cty.SoNgayLamTB);
                txtLuong.Text = luong.ToString();
            }
            else
            {
                txtLuong.Text = objList.MucLuong.ToString();
            }
            
        }

        protected void ddlKhuVuc_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadLo(ddlKhuVuc.SelectedValue);
            LoadTienLuongLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            if (ddlNhanVien.SelectedIndex != -1)
            {
                LoadLuongNV(ddlNhanVien.SelectedValue);
            }    
            upnlGrid.Update();
        }

        protected void ddlLo_SelectedIndexChanged(object sender, EventArgs e)
        {
            ClearForm();
            LoadTienLuongLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            LoadNhanVienLo(ddlLo.SelectedValue, ConvertUtil.ToDateTime(lbngayhientai.Text.Trim()).Value);
            if (ddlNhanVien.SelectedIndex != -1)
            {
                LoadLuongNV(ddlNhanVien.SelectedValue);
            }    
            upnlGrid.Update();
        }

        protected void ddlNhanVien_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlNhanVien.SelectedIndex != -1)
            {
                LoadLuongNV(ddlNhanVien.SelectedValue);
            }            
        }

        public string CheckNghiPhep(object obj)
        {
            if (obj == null)
            {
                return "Không";
            }
            bool b = bool.Parse(obj.ToString());
            if (b)
                return "Có";
            else
                return "Không";
        } 
    }
}